package com.pallass.admin.controller;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.pallass.admin.domain.SysResource;
import com.pallass.admin.service.SysResourceService;
import com.pallass.common.controller.BaseController;
import com.pallass.common.jpa.criteria.OperatorType;
import com.pallass.common.jpa.domain.ListSpecificationBuilder;
import com.pallass.security.CustomerUser;
import com.pallass.utils.RequestResult;

/**
 * 资源(菜单)
 * 
 * @author Houor
 *
 * @createTime: 2017-03-01 11:14
 */
@Controller
@RequestMapping("/admin/resource")
public class ResourceController extends BaseController {

	private static Logger logger = LoggerFactory.getLogger(ResourceController.class);

	@Autowired
	private SysResourceService resourceService;

	@RequestMapping(value = "/index")
	public String index(Model model) {
		model.addAttribute("purl", "admin/resource");
		return "admin/resource";
	}

	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@ResponseBody
	public Page<SysResource> list() {
		ListSpecificationBuilder<SysResource> builder = new ListSpecificationBuilder<SysResource>();
		String resourceName = request.getParameter("resourceName");
		if (StringUtils.isNotBlank(resourceName)) {
			builder.add("resourceName", OperatorType.LIKE, resourceName);
		}

		return resourceService.findAll(builder.generateListSpecification(), getPageRequest());
	}

	@RequestMapping(value = "/lists")
	@ResponseBody
	public RequestResult lists(ModelMap map) {
		List<SysResource> results = resourceService.findAllWithoutButton();

		// 构造父子树
		SysResource root = new SysResource();
		root.setId(0);
		root.setResourceName("根资源");
		root.setOpen(true);

		for (SysResource sr : results) {
			if (sr.getParent() == null) {
				root.getChildren().add(sr);
			} else {
				sr.getParent().getChildren().add(sr);
				sr.setParent(null);
			}
		}

		return RequestResult.success().put("root", root);
	}

	@RequestMapping(value = "/save")
	@ResponseBody
	public RequestResult save(@RequestBody SysResource resource) {
		if (StringUtils.isBlank(resource.getResourceName())) {
			return RequestResult.failure("资源名称不能为空");
		}

		if (StringUtils.isBlank(resource.getResourceUrl())) {
			return RequestResult.failure("资源Url不能为空");
		}

		if (StringUtils.isBlank(resource.getPermissions())) {
			return RequestResult.failure("资源权限不能为空");
		}

		// clear root parent
		if (resource.getParent().getId() == 0)
			resource.setParent(null);
		resourceService.save(resource);
		return RequestResult.success("添加资源成功");
	}

	@RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
	@ResponseBody
	public SysResource edit(@PathVariable Integer id) {
		return resourceService.findOne(id);
	}

	@RequestMapping(value = "/update")
	@ResponseBody
	public RequestResult update(@RequestBody SysResource resource) {
		if (StringUtils.isBlank(resource.getResourceName())) {
			return RequestResult.failure("资源名称不能为空");
		}

		if (StringUtils.isBlank(resource.getResourceUrl())) {
			return RequestResult.failure("资源Url不能为空");
		}

		if (StringUtils.isBlank(resource.getPermissions())) {
			return RequestResult.failure("资源权限不能为空");
		}
		resourceService.update(resource);
		return RequestResult.success("修改资源成功");
	}

	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	@ResponseBody
	public RequestResult delete(@RequestBody Integer ids[]) {
		try {
			resourceService.deleteByIdArray(ids);
		} catch (org.springframework.dao.DataIntegrityViolationException e) {
			logger.info("该资源已被引用, 请确认后再删除");
			return RequestResult.failure("该资源已被引用, 请确认后再删除");
		}

		return RequestResult.success("删除资源成功");
	}

	@RequestMapping(value = "/menus", method = RequestMethod.GET)
	@ResponseBody
	public List<SysResource> menus() {
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		if (auth == null) {
			return null;
		}
		CustomerUser principal = (CustomerUser) auth.getPrincipal();
		if (principal == null) {
			return null;
		}
		return principal.getMenus();
	}

}
